import { Injectable } from '@nestjs/common';
import { CreateKitDto, KitTag, KitTags } from './dto/create-kit.dto';
import { UpdateKitDto } from './dto/update-kit.dto';
import { QueryDto } from './dto/query.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Kit } from './entities/kit.entity';
import { FindOptionsWhere, Raw, Repository } from 'typeorm';

@Injectable()
export class KitService {
  constructor(
    @InjectRepository(Kit) private readonly kitRepository: Repository<Kit>,
  ) {}

  async create(createKitDto: CreateKitDto) {
    const exit = await this.kitRepository.findOneBy({
      name: createKitDto.name,
    });

    if (exit) {
      return {
        code: 400,
        data: null,
        message: 'kit已存在',
      };
    }

    const kit = this.kitRepository.create({
      ...createKitDto,
      action: {
        likes: 0,
        collects: 0,
        uses: 0,
      },
    });

    const savedKit = await this.kitRepository.save(kit);

    return {
      code: 200,
      data: {
        id: savedKit.id,
        name: savedKit.name,
        type: savedKit.type,
        description: savedKit.description,
        createdAt: savedKit.createAt,
      },
      message: '创建成功',
    };
  }

  async findAll(query: QueryDto) {
    // 当没有任何查询参数时返回全部结果
    if (Object.keys(query).length === 0) {
      const [data, total] = await this.kitRepository.findAndCount({
        select: ['id', 'name', 'type', 'description', 'tag', 'createAt'],
        take: 10,
      });
      return { rows: data, total };
    }
    const { pageNum = 1, pageSize = 10, keywords = '', ...rest } = query;
    // 构建查询条件，确保类型安全
    const where: FindOptionsWhere<Kit> = {};
    if (rest.name) {
      where.name = rest.name;
    } else if (keywords) {
      where.name = Raw(
        (alias) => `${alias} REGEXP :pattern OR description REGEXP :pattern`,
        { pattern: keywords.replace(/,/g, '|') },
      );
    }
    if (rest.tag) {
      where.tag = rest.tag as unknown as NonNullable<KitTag>;
    }

    const [data, total] = await this.kitRepository.findAndCount({
      select: [
        'id',
        'name',
        'type',
        'description',
        'tag',
        'createAt',
        'imageUrl',
      ],
      where,
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
    });

    return {
      rows: data,
      total,
    };
  }

  findOne(id: number) {
    return this.kitRepository.findOneBy({ id });
  }

  async update(id: number, updateKitDto: UpdateKitDto) {
    return await this.kitRepository.update(id, updateKitDto);
  }

  remove(id: number) {
    return this.kitRepository.delete(id);
  }
}
